home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 9 / Night Owl CD-ROM (NOPV9) (Night Owl Publisher) (1993).ISO / 009a / snpd0493.zip / TRIM.C < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  79 lines

  1. /*
  2. **  TRIM.C - Remove leading, trailing, & excess embedded spaces
  3. **
  4. **  public domain by Bob Stout
  5. */
  6.  
  7. #include <ctype.h>
  8. #include <string.h>
  9.  
  10. #define NUL '\0'
  11.  
  12. char *trim(char *str)
  13. {
  14.       char *ibuf = str, *obuf = str;
  15.       int i = 0, cnt = 0;
  16.  
  17.       /*
  18.       **  Trap NULL
  19.       */
  20.  
  21.       if (str)
  22.       {
  23.             /*
  24.             **  Remove leading spaces (from RMLEAD.C)
  25.             */
  26.  
  27.             for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf)
  28.                   ;
  29.             if (str != ibuf)
  30.                   memmove(str, ibuf, ibuf - str);
  31.  
  32.             /*
  33.             **  Collapse embedded spaces (from LV1WS.C)
  34.             */
  35.  
  36.             while (*ibuf)
  37.             {
  38.                   if (isspace(*ibuf) && cnt)
  39.                         ibuf++;
  40.                   else
  41.                   {
  42.                         if (!isspace(*ibuf))
  43.                               cnt = 0;
  44.                         else
  45.                         {
  46.                               *ibuf = ' ';
  47.                               cnt = 1;
  48.                         }
  49.                         obuf[i++] = *ibuf++;
  50.                   }
  51.             }
  52.             obuf[i] = NUL;
  53.  
  54.             /*
  55.             **  Remove trailing spaces (from RMTRAIL.C)
  56.             */
  57.  
  58.             while (--i >= 0)
  59.             {
  60.                   if (!isspace(obuf[i]))
  61.                         break;
  62.             }
  63.             obuf[++i] = NUL;
  64.       }
  65.       return str;
  66. }
  67.  
  68. #ifdef TEST
  69.  
  70. #include <stdio.h>
  71.  
  72. main(int argc, char *argv[])
  73. {
  74.       printf("trim(\"%s\") ", argv[1]);
  75.       printf("returned \"%s\"\n", trim(argv[1]));
  76. }
  77.  
  78. #endif /* TEST */
  79.